from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from app.core.security import create_access_token
from app.crud.user import get_user_by_username
from app.schemas.user import User,LoginUser
from app.utils.hashing import verify_password
from app.db.session import get_db

router = APIRouter()

@router.post("/token")
def login(userpwd: LoginUser, db: Session = Depends(get_db)):
    user = get_user_by_username(db, userpwd.username)
    if not user or not verify_password(userpwd.password, user.password_hash):
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token = create_access_token(data={"sub": user.username})
    return {"access_token": access_token, "token_type": "bearer"}